import { Injectable } from '@angular/core';
import { ConnectionBackend, RequestOptions, Request, RequestOptionsArgs, Response, Http, RequestMethod } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { Router } from '@angular/router';
import { ConfigService } from '../../core/common/config.service';
@Injectable()
export class InterceptedHttp extends Http {
  constructor(backend: ConnectionBackend, defaultOptions: RequestOptions, private config: ConfigService, private router: Router) {
    super(backend, defaultOptions);
  }
    private mergeOptions(defaultOpts, providedOpts, method, url) {
    const /** @type {?} */ newOptions = defaultOpts || [];
    if (providedOpts) {
      // Hack so Dart can used named parameters
      return newOptions.merge(new RequestOptions({
        method: providedOpts.method || method,
        url: providedOpts.url || url,
        search: providedOpts.search,
        headers: providedOpts.headers,
        body: providedOpts.body,
        withCredentials: providedOpts.withCredentials,
        responseType: providedOpts.responseType
      }));
    }
    return newOptions.merge(new RequestOptions({ method: method, url: url }));
  }
  public request(request): Observable<Response> {
    const token = window.sessionStorage.getItem('token');
    if (token) {
      const tokenName = this.config.get('auth.token');
      request.headers.set(tokenName, token);
    }
    const observer = super.request(request).map((resp: Response) => {
      if (resp.json() && resp.json().code === '1702') {
        this.router.navigate(['/login', {loginError: '您已长时间没有操作，请重新登录！'}], {skipLocationChange: true});
        throw new Error('您已长时间没有操作，请重新登录！');
      }
      return resp;
    });
    return observer;
  }
  public get(url: string | Request, options?: RequestOptions): Observable<Response> {
    return this.request(new Request(this.mergeOptions(this._defaultOptions, options, RequestMethod.Get, url)));
  }
  public post(url: string | Request, body: any, options?: RequestOptionsArgs): Observable<Response> {
    return this.request(new Request(this.mergeOptions(this._defaultOptions.merge(new RequestOptions({ body: body })),
      options, RequestMethod.Post, url)));
  }
  public put(url: string | Request, body: any, options?: RequestOptionsArgs): Observable<Response> {
    return this.request(new Request(this.mergeOptions(this._defaultOptions.merge(new RequestOptions({ body: body })),
      options, RequestMethod.Post, url)));
  }
}
